package com.kanhan.altvalidator.tool;

import java.util.ArrayList;

import org.htmlparser.*;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.kanhan.altvalidator.Bridge;
import com.kanhan.altvalidator.EntityImage;

public class Checker {
	public static final String[] rg = { "" };

	public static boolean isHtml(String url) {
		return url.toUpperCase().endsWith(".HTML")
				|| url.toUpperCase().endsWith(".HTM");
	}

	public static boolean isText(String path) {
		return path.toLowerCase().endsWith(".txt");
	}

	public static ArrayList<EntityImage> doFind(String url) {
		ArrayList<EntityImage> eiList = new ArrayList<EntityImage>();
		try {
			Parser p = new Parser(url);
			p.setEncoding(EncodeGoter.getEncode(url));
			NodeFilter filter = new TagNameFilter("IMG");
			NodeList nodes = p.extractAllNodesThatMatch(filter);
			Node eachNode = null;
			ImageTag imageTag = null;
			EntityImage ei = null;
			if (nodes != null)
				for (int i = 0; i < nodes.size(); i++) {
					eachNode = (Node) nodes.elementAt(i);
					if (eachNode instanceof ImageTag) {
						imageTag = (ImageTag) eachNode;
						if (!isValidator(imageTag.getAttribute("alt"))) {
							ei = new EntityImage();
							ei.setParentUrl(url);
							ei.setLineNum(imageTag.getEndingLineNumber());
							ei.setSrc(imageTag.getAttribute("src"));
							ei.setAlt(imageTag.getAttribute("alt"));
							eiList.add(ei);
						}
					}
				}
		} catch (ParserException e) {
			Bridge.errlList.add(url);
			e.printStackTrace();
		} catch (Exception e) {
			Bridge.errlList.add(url);
			e.printStackTrace();
		}
		return eiList;
	}

	public static boolean isValidator(String str) {
		if (str == null)
			return false;
		if(str.equals(""))
			return false;
		if (Bridge.patlList != null)
			for (String x : Bridge.patlList) {
				if (str.equals(x))
					return false;
			}
		return true;
	}

	public static boolean altIsOK(EntityImage ei) {
		return altIsOK(ei.getAlt());
	}

	public static boolean altIsOK(String str) {
		return true;
	}

}
